package 代码随想录.回溯.组合总和III;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LeetCode216 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(n, k, 1, 0);
        return result;
    }

    public void backTracking(int targetSum, int k, int startIndex, int sum) {
        if (sum > targetSum) {  //剪枝
            return;
        }
        if (path.size() == k) {
            if (sum == targetSum) {//是否满足条件
                result.add(new ArrayList<>(path));
            }
        }
        for (int i = startIndex; i <= 9; i++) {
            path.add(i);
            sum += i;
            backTracking(targetSum, k, i + 1, sum);
            //回溯
            path.removeLast();
            sum -= i;
        }
    }

    public static void main(String[] args) {
        LeetCode216 code = new LeetCode216();
        List<List<Integer>> list = code.combinationSum3(3, 9);
        System.out.println(list);
    }
}
